package com.haredot.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haredot.entity.Position;
import com.haredot.exception.ServiceAccessException;
import com.haredot.mapper.PositionMapper;
import com.haredot.service.PositionService;
import com.haredot.vo.PageVo;
import com.haredot.vo.R;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
@Transactional(rollbackFor = Exception.class)
public class PositionServiceImpl implements PositionService {

    @Resource
    private PositionMapper positionMapper ;

    @Override
    public R<PageVo> queryPositionsByPage(PageVo pageVo, Map<String, Object> params) {

        PageInfo<Position> pageInfo =PageHelper.startPage(pageVo)
                .doSelectPageInfo(()-> positionMapper.findPositionsByCondition(params));

        pageVo.setList(pageInfo.getList()).setTotal(pageInfo.getTotal());
        return R.<PageVo>ok().data(pageVo);
    }

    @Override
    public R<?> savePosition(Position position) {
        // 根据职务名查询
        Position byName = positionMapper.findPositionByName(position.getName());

        if (byName != null) return R.fail(R.StatusCode.BAD).data(Map.of("name", "职务名已经存在"));

        int len = positionMapper.insert(position);

        if (len != 1) throw new ServiceAccessException("保存职务失败、期待影响1行、实际影响" + len + "行");

        return R.ok().build();
    }

    @Override
    public R<?> updatePosition(Position position) {
        // 根据职务名查询
        Position byName = positionMapper.findPositionByName(position.getName());

        if (byName != null && !Objects.equals(position.getId(), byName.getId())) {
            return R.fail(R.StatusCode.BAD).data(Map.of("name", "职务名已经存在"));
        }

        int len = positionMapper.update(position);

        if (len != 1) throw new ServiceAccessException("修改职务失败、期待影响1行、实际影响" + len + "行");

        return R.ok().build();
    }

    @Override
    public R<?> removePosition(Long id) {

        int len = positionMapper.deleteById(id);

        if (len != 1) throw new ServiceAccessException("删除职务失败、期待影响1行、实际影响" + len + "行");

        return R.ok().build();
    }

    @Override
    public R<?> removeBatchPosition(List<Long> ids) {

        int len = positionMapper.batchDeleteByIds(ids);

        if (len != ids.size()) throw new ServiceAccessException("批量删除职务失败、期待影响"+ ids.size()+"行、实际影响" + len + "行");

        return R.ok().build();
    }
}
